<template>
  <div class="dashboard-container">
    <Add v-if="data.addShow" openKey="addShow" :editData="data.editData" @setMData="setMData"></Add>
    <div class="serach-option">
      <el-form :inline="true" :model="searchForm" class="search-form" ref="searchFormDom" label-width="100px">
        <el-form-item label="项目名称" prop="projName">
          <el-input v-model="searchForm.projName" placeholder="请输入项目名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="项目标识号" prop="projKey">
          <el-input v-model="searchForm.projKey" placeholder="请输入项目标识号" clearable></el-input>
        </el-form-item>
        <div v-show="false">
          <el-form-item prop="pageNum"> </el-form-item>
          <el-form-item prop="pageSize"> </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="action-buttons">
      <el-button type="primary" @click="openAddDialog">增加项目</el-button>
    </div>

    <div class="project-container">
      <el-table
        v-loading="loading"
        :data="projectList"
        border
        style="width: 100%; height: calc(100% - 120px)"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        :row-key="row => row.id"
        ref="projectTable"
        highlight-current-row
      >
        <el-table-column prop="id" label="项目ID" width="100"></el-table-column>
        <el-table-column prop="projName" label="项目名称" min-width="240"></el-table-column>
        <el-table-column prop="projKey" label="项目标识号" min-width="200"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="200"></el-table-column>
        <el-table-column prop="fileCount" label="文件数量" min-width="120"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleAdjust(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="small"
              type="info"
              link
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="searchForm.pageNum" 
        v-model:limit="searchForm.pageSize" :total="total" @pagination="handleSearch" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as projectAPI from '@/api/project'
import Add from './Add.vue' // 项目添加组件

const route = useRoute()
const router = useRouter()

// 添加分页相关变量和方法
const searchFormDom = ref(null)

// 组件状态管理
const data = reactive({
  addShow: false, // 控制添加项目对话框显示
  editData: null
})
const adjustRef = ref(null)
const projectList = ref([])
const selectedProjects = ref([])
const total = ref(0)
const searchForm = ref({
  projName: undefined,
  projKey: undefined,
  pageNum: 1,
  pageSize: 10
})
const loading = ref(false)

/**
 * 处理子组件传递的数据变更事件
 * @param {string} type - 数据类型标识
 * @param {any} value - 新值
 */
function setMData(type, value) {
  if (type === 'refreshList') {
    loading.value = true  // 添加加载状态
    fetchProjectList().then(() => {
      loading.value = false
    }).catch(error => {
      loading.value = false
    })
  } else {
    data[type] = value;
  }
}



/**
 * 获取项目列表数据
 * 自动区分开发/生产环境
 * @returns {Promise<void>}
 */
const fetchProjectList = async () => {
  loading.value = true  // 添加加载状态
  const res = await projectAPI.getProjectList(searchForm.value)
  loading.value = false
  if (route.query.projKey) {
    projectList.value = res.data.filter(project => project.projKey === route.query.projKey)
  } else {
    projectList.value = res.data
  }
}

/**
 * 处理项目搜索
 * 支持按项目名称或标识号筛选
 * 自动区分开发/生产环境
 * @returns {Promise<void>}
 */
const handleSearch = async () => {
  fetchProjectList()
}

/**
 * 打开添加项目对话框
 */
const openAddDialog = () => {
  data.editData = null;
  data.addShow = true
}
const handleAdjust = (row) => {
  data.addShow = true
  data.editData = row;
}
/**
 * 重置搜索表单并刷新列表
 */
const handleReset = () => {
  searchFormDom.value.resetFields();
  fetchProjectList()
}

/**
 * 查看项目详情
 * @param {Object} row - 项目数据对象
 * @param {string} row.projKey - 项目唯一标识
 */
const handleView = (row) => {
  console.log('查看项目:', row.id, row.projKey, row.name) // 调试日志
  // 使用PROJ-{id}格式的projectId，与Mock数据保持一致
  const projectId = row.projKey ? row.projKey : `PROJ-${row.id.toString().padStart(3, '0')}`
  router.push({
    name: 'ProjectDashboard',
    params: {
      id: projectId
    },
    query: {
      projectName: row.name // 额外传递项目名称
    }
  })
}

// 组件挂载时获取项目列表
onMounted(() => {
  fetchProjectList()
})

</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-width: 1200px;
}

.project-container {
  background: #fff;
  min-width: 1200px;
}
.card-header {
  font-size: 18px;
  font-weight: bold;
  min-width: 1200px;
}

.action-buttons {
  margin-bottom: 20px;
}
</style>
